import React, { useRef } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../app/hooks";
import { setAvator } from "../../app/user/userSlice";
import axios from "axios";
const Index: React.FC = () => {
  const avator = useAppSelector((state) => state.user.avator);
  const nickname = useAppSelector((state) => state.user.nickname);
  const username = useAppSelector((state) => state.user.username);
  const input = useRef<HTMLInputElement | null>(null);
  const dispatch = useDispatch();

  const onChange = () => {
    if (input.current && input.current.files) {
      const file = input.current.files[0];
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.addEventListener("load", () => {
        dispatch(setAvator(fileReader.result as string));
      });
    }
  };

  const onChange1 = async () => {
    if (input.current && input.current.files) {
      const file = input.current.files[0];

      const formData = new FormData();
      formData.append("chunk", file, file.name);

      const resp = await axios.post(`/api/upload/avator/${username}`, formData);
      console.log(resp.data);
      dispatch(setAvator(resp.data.data.url))
    }
  };

  return (
    <div>
      <input
        ref={input}
        type="file"
        style={{ display: "none" }}
        onChange={onChange1}
      />
      <div
        style={{
          display: "flex",
          justifyContent: "space-around",
          alignItems: "center",
        }}
      >
        <img
          src={avator}
          alt=""
          style={{
            borderRadius: "50%",
            width: 80,
            height: 80,
            border: "1px solid #ccc",
          }}
          onClick={() => input.current?.click()}
        />
        <h2>{nickname}</h2>
      </div>
    </div>
  );
};

export default Index;
